#include "Ringbufferbase.h"





CRingbufferBase :: CRingbufferBase(int maxbuff_len)
{
    memset(&m_ringbuf, 0, sizeof(m_ringbuf));
    m_ringbuf.data = (char *)malloc(maxbuff_len);
    m_ringbuf.datalen = maxbuff_len;
}


CRingbufferBase :: ~CRingbufferBase()
{
    free(m_ringbuf.data);
    m_ringbuf.data = NULL;
}


int CRingbufferBase :: RingbuffRead(char *readdata, int readlen)
{
   int remainlen = RingbuffRemainCount();
   readlen =  remainlen >= readlen ? readlen : remainlen;
   if(!RingbuffIsempty())
   {
        for(int i =0; i < readlen ; i++)
                {
                    readdata[i] = m_ringbuf.data[m_ringbuf.out_flg];
                    //溢出后要从0开始置位
                    m_ringbuf.out_flg = (m_ringbuf.out_flg+1) % m_ringbuf.datalen;
            }

   }
   else
       return 0;
   return readlen;
}


int CRingbufferBase :: RingbuffWrite(char *writedata, int writelen)
{
    int remainwritelen = m_ringbuf.datalen -  RingbuffRemainCount();
    writelen = writelen > remainwritelen ? remainwritelen : writelen;
    if(!RingbuffIsFull())
    {
         for(int i =0; i < writelen; i++)
            {
                m_ringbuf.data[m_ringbuf.in_flg] = writedata[i];
                //溢出后要从0重新计算位置，此处取余操作
                m_ringbuf.in_flg = (m_ringbuf.in_flg + 1) % m_ringbuf.datalen;
        }
    }
    else
       return 0;
    return writelen;
}


int CRingbufferBase :: RingbuffIsempty()
{
   return (m_ringbuf.in_flg == m_ringbuf.out_flg);
}

int CRingbufferBase :: RingbuffIsFull()
{
    return (m_ringbuf.out_flg == (m_ringbuf.in_flg + 1)%m_ringbuf.datalen);
}


int CRingbufferBase :: RingbuffRemainCount()
{

   return (m_ringbuf.in_flg - m_ringbuf.out_flg + m_ringbuf.datalen)%m_ringbuf.datalen;

}